package com.example.tuling;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

public class RedisKeyFilter {

    private static final String PREFIX = "activity:1204:user:rank_reward:status:";
    private static final int BATCH_SIZE = 10;

    // 需要排除的 uid 列表
    private static final Set<String> EXCLUDE_UIDS = new HashSet<>(Arrays.asList(
        "1955234849294368768",
        "1964470263581413376",
        "1965863196204638208",
        "1969012333562081280",
        "1970895097439236096",
        "1965155595523756032",
        "1969974143353794560",
        "1969974832625135616",
        "1966524715604156416",
        "1961835938804285440",
        "1955241749247016960",
        "1968268937281314816",
        "1958100904842493952",
        "1955166551667752960",
        "1969422969021968384",
        "1957363109299744768",
        "1957363362606739456",
        "1957446726931050496",
        "1957453097395154944",
        "1969071606614765568",
        "1957435937033547776",
        "1955223242644242432",
        "1955987768447590400",
        "1957519937882157056",
        "1955162758721421312",
        "1970332930602217472",
        "1959137726335025152",
        "1963290480744878080",
        "1957018005188763648",
        "1955481328760111104",
        "1958843756799459328",
        "1955164403454820352",
        "1970913628742266880",
        "1956572222186315776",
        "1955226667889311744",
        "1955600394535157760"
    ));

    public static void main(String[] args) throws IOException {
        // 1) 读取 keys.txt：优先 resources，其次工作目录
        List<String> lines = readKeysTxt();

        // 2) 解析所有符合前缀的 key（不再依赖“每3行第3行”）
        int totalLines = lines.size();
        List<String> parsedKeys = lines.stream()
            .map(String::trim)
            .filter(s -> s.startsWith(PREFIX))
            .collect(Collectors.toList());

        // 3) 去重（保持原始顺序）
        LinkedHashSet<String> uniqueKeys = new LinkedHashSet<>(parsedKeys);

        // 4) 过滤排除 UID，同时统计命中排除的数量
        int excludeHit = 0;
        List<String> kept = new ArrayList<>();
        for (String key : uniqueKeys) {
            String[] parts = key.split(":");
            // 期望形如: activity:1204:user:rank_reward:status:{uid}:{suffix}
            if (parts.length >= 6) {
                String uid = parts[5];
                if (EXCLUDE_UIDS.contains(uid)) {
                    excludeHit++;
                    continue;
                }
                kept.add(key);
            }
        }

        // 5) 每 10 个 key 拼接一条 DEL 命令（每行一条命令）
        List<String> delCommands = new ArrayList<>();
        for (int i = 0; i < kept.size(); i += BATCH_SIZE) {
            int end = Math.min(i + BATCH_SIZE, kept.size());
            delCommands.add("DEL " + String.join(" ", kept.subList(i, end)));
        }

        // 6) 写出到工作目录 del_keys.txt
        String outputFile = "del_keys.txt";
        Files.write(Paths.get(outputFile), delCommands);

        // 7) 打印统计信息，帮助你核对“为什么只有 88 个”
        System.out.println("====== 统计信息 ======");
        System.out.println("原始行数: " + totalLines);
        System.out.println("解析到的key(含重复): " + parsedKeys.size());
        System.out.println("去重后的key: " + uniqueKeys.size());
        System.out.println("命中排除UID数量: " + excludeHit);
        System.out.println("最终输出的key数量: " + kept.size());
        System.out.println("生成命令行数(每行最多" + BATCH_SIZE + "个key): " + delCommands.size());
        System.out.println("结果已写入: " + outputFile);
    }

    private static List<String> readKeysTxt() throws IOException {
        // 先从 resources 读
        InputStream in = RedisKeyFilter.class.getClassLoader().getResourceAsStream("keys.txt");
        if (in != null) {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
                return br.lines().collect(Collectors.toList());
            }
        }
        // 回退到工作目录
        if (Files.exists(Paths.get("keys.txt"))) {
            return Files.readAllLines(Paths.get("keys.txt"));
        }
        throw new FileNotFoundException("keys.txt not found (resources 或 工作目录都不存在)");
    }
}
